package com.atguigu.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.properties.OrderProperties;
import com.atguigu.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//@RequestMapping("/api/order")
@RestController
//@RefreshScope //自动刷新nacos的配置文件信息
public class OrderController {

    @Autowired
    private OrderService orderService;

    /*@Value("${order.timeout}")
    String orderTimeout;
    @Value("${order.auto-confirm}")
    String orderAutoConfirm;*/
    @Autowired
    private OrderProperties orderProperties;

    @GetMapping("/config")
    public String config(){
        return "order.timeout="+orderProperties.getTimeout()+
                ",   order.auto-confirm="+orderProperties.getAutoConfirm()+
                ",   order.db.url="+orderProperties.getDbUrl();
    }
    //创建订单
    @GetMapping("/create")
    public Order createOrder(@RequestParam("productId") Long productId, @RequestParam("userId") Long userId) {

        Order order = orderService.createOrder(productId, userId);
        return order;
    }

    /**
     * 秒杀
     * @param productId
     * @param userId
     * @return
     */
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", blockHandler = "seckillFallBack")
    public Order seckill(@RequestParam("productId") Long productId, @RequestParam("userId") Long userId) {

        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }
    public Order seckillFallBack(Long productId, Long userId, BlockException e) {
        System.out.println("seckillFallBack..............");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息："+e.getClass());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb(){
        return "writeDb success..";
    }

    @GetMapping("/readDb")
    public String readDb(){
        return "readDb success..";
    }
}
